package org.dant.ant.extension.tasks;

import java.util.*;
import java.io.*;

import org.apache.tools.ant.TaskContainer;
import org.apache.tools.ant.Task;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.dant.ant.extension.tasks.commands.AntCommand;
import org.dant.ant.extension.tasks.internal.RemoteCommand;
import org.dant.ant.extension.utils.StringUtils;
import org.dant.ant.extension.tasks.internal.Endpoint;

public class RemoteAnt extends RemoteTask implements TaskContainer {

  private Vector nestedTasks = new Vector();
  private String buildContents = null;
  private ByteArrayOutputStream outstream = new ByteArrayOutputStream();

  protected File dir = null;
  protected String dirstring = null;
  
  public RemoteAnt() {
    rcmd = new AntCommand();
  }

  public void setDir(String dir) {
    dirstring = dir;
    this.dir = getProject().resolveFile(dir, getProject().getBaseDir());
  }

  public File getDir() {
    return this.dir;
  }


  public String getBuildContents() {
    return buildContents;
  }

  private void parse() throws Exception {
	TransformerFactory tFactory = TransformerFactory.newInstance();
    String defs = "/org/dant/ant/extension/tasks/xslt/spawn.xslt";
	Transformer transformer = tFactory.newTransformer(new StreamSource(this.getClass().getResourceAsStream(defs)));

    String targetName = getOwningTarget().getName();
    String taskName = getTaskName();

    transformer.setParameter("TARGET_ID", targetName);
    transformer.setParameter("TASK_ID", taskName);

    File source = StringUtils.parseFileName(getProject().getBaseDir(), getLocation().toString());

	transformer.transform(new StreamSource(source), new StreamResult(outstream));
    buildContents = outstream.toString();
    System.out.println(buildContents);
  }

  public void initialize() throws Exception {
    parse();
    super.initialize();
  }

  public void addTask(Task nestedTask) {
    nestedTasks.addElement(nestedTask);
  }

  public void resolveDir() throws IOException {
    for (Iterator iter=destHosts.keySet().iterator(); iter.hasNext();) {
      Endpoint ep = (Endpoint) iter.next();
      RemoteCommand request = (RemoteCommand)destHosts.get(ep);
      File basedir = ep.getBaseDir();
      File antdir = (dirstring == null) ? null : new File(dirstring);
      if (basedir == null || (antdir != null && antdir.isAbsolute())) continue;
      File absolutePath = fu.resolveFile(basedir, dirstring);
      request.appendParameters("dir", absolutePath);
    }
  }
}
